package com.zj.base.httpclien;

import android.os.AsyncTask;

import com.zj.base.permission.ConfigurationModules;
import com.zj.base.permission.interfaces.OnPermissionCheckListener;
import com.zj.base.permission.manifests.PermissionsManifest;
import com.zj.base.utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhaojie on 2018/4/10.
 */


@SuppressWarnings("unused")
public class PostRequestBuilder<T> extends HttpRequestBuilder<T> {

    PostRequestBuilder(int reqCode, HttpClient<T> client) {
        super(reqCode, client);
    }

    @Override
    HttpMethod getMethod() {
        return HttpMethod.post;
    }

    /**
     * compare a default cookies in getDefaultCookie();
     */
    public PostRequestBuilder<T> cookie(Map<String, String> cookie) {
        client.setCookies(cookie);
        return this;
    }

    public PostRequestBuilder<T> url(String url) {
        client.setUrl(url);
        return this;
    }

    public PostRequestBuilder<T> timeOut(long t) {
        client.setTimeOut(t);
        return this;
    }

    public PostRequestBuilder<T> params(Map<String, String> params) {
        client.setParams(params);
        return this;
    }

    public void upLoad(String upKey, final Map<String, File> files, final OnFileCheeked onFileCheeked) {
        client.setType(HttpClient.TYPE.upLoad);
        client.setUploadKey(upKey);
        Map<String, Boolean> pers = new HashMap<>();
        pers.put(PermissionsManifest.READ_EXTERNAL_STORAGE, true);
        pers.put(PermissionsManifest.WEITE_EXTERNAL_STORAGE, true);
        client.getDataInterface().onPermissionsCheck(pers, new OnPermissionCheckListener() {
            @Override
            public void startCheck(ConfigurationModules modules) {
                ToastUtils.show("必要权限检测中，请稍候...");
            }

            @Override
            public void result(ConfigurationModules modules, State state) {

            }

            @Override
            public void onSuccess(List<ConfigurationModules> modulesList) {
                upLoad(files, onFileCheeked);
            }
        });
    }

    /**
     * permissions granted, upload files
     */
    public void upLoad(final Map<String, File> files, final OnFileCheeked onFileCheeked) {
        new CheckFileExitsAsync(files, new OnFileCheek() {
            @Override
            public void onCheeked(Map<String, File> map) {
                if (map.size() != files.size()) {
                    List<String> list = new ArrayList<>();
                    for (Map.Entry<String, File> e : files.entrySet()) {
                        if (!map.containsKey(e.getKey()))
                            list.add(e.getValue().getPath());
                    }
                    if (onFileCheeked == null || onFileCheeked.onFailFiles(list, "请检查以下文件是否存在！")) {
                        client.setUploadParams(map);
                        send();
                    }
                } else {
                    if (onFileCheeked == null || onFileCheeked.success()) {
                        client.setUploadParams(map);
                        send();
                    }
                }
            }
        }).execute();
    }

    public interface OnFileCheek {
        void onCheeked(Map<String, File> map);
    }

    public interface OnFileCheeked {

        void startCheek();

        /**
         * the file will upload if returns true;
         */
        boolean success();

        /**
         * the success file will upload if returns true,ignore fail;
         */
        boolean onFailFiles(List<String> failDocuments, String msg);
    }

    public static class CheckFileExitsAsync extends AsyncTask<String, Integer, Map<String, File>> {

        CheckFileExitsAsync(Map<String, File> params, OnFileCheek onFileCheek) {
            this.onFileCheek = onFileCheek;
            this.params = params;
        }

        private final OnFileCheek onFileCheek;
        private final Map<String, File> params;


        @Override
        protected Map<String, File> doInBackground(String... strs) {
            Map<String, File> resultMap = new HashMap<>();
            for (Map.Entry<String, File> entry : params.entrySet()) {
                if (entry.getValue().exists()) resultMap.put(entry.getKey(), entry.getValue());
            }
            return resultMap;
        }

        @Override
        protected void onPostExecute(Map<String, File> result) {
            onFileCheek.onCheeked(result);
        }
    }


}
